package com.jia.videos.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jia.videos.entity.Category;
import com.jia.videos.mapper.CategoryMapper;
import com.jia.videos.service.CategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author dujiajia
 * @since 2020-12-20
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Override
    public List<Category> getAll() {
        QueryWrapper<Category> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("sort");
        List<Category> categories = baseMapper.selectList(wrapper);
        return categories;
    }

    @Override
    public List<Category> selectTree() {
        // 1查询全部的 分类
        List<Category> categories = baseMapper.selectList(null);

        // 2组成树形结构
        List<Category> tree = categories.stream().filter(categoryEntity ->
                categoryEntity.getParentId() == 0
        ).map(menu -> {
            menu.setChildren(getChildrens(menu, categories));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return tree;
    }

    // 递归查找当前菜单的子菜单
    private List<Category> getChildrens(Category root, List<Category> all) {
        List<Category> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentId() == root.getId();
        }).map(categoryEntity -> {
            // 递归查找子菜单
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return children;
    }

}
